package cn.sinata.xldutils_kotlin.rxutils

import cn.sinata.xldutils_kotlin.activity.BaseActivity
import cn.sinata.xldutils_kotlin.fragment.BaseFragment
import io.reactivex.subscribers.DisposableSubscriber
import java.lang.ref.WeakReference

/**
 *
 */
abstract class ResultSubscriber<T> : DisposableSubscriber<T> {
    protected var activities : WeakReference<BaseActivity>?=null
    protected var fragments : WeakReference<BaseFragment>?=null
    constructor(activity:  BaseActivity)  {
        activities = WeakReference(activity)
        addToComposite(activity)
    }

    constructor(fragment: BaseFragment){
        fragments = WeakReference(fragment)
        addToComposite(fragment)
    }

    override abstract fun onNext(t: T)

    override fun onComplete() {

    }

    override fun onError(t: Throwable) {

    }

    private fun addToComposite(activity: BaseActivity) {
        activity.compositeDisposable.add(this)
    }

    private fun addToComposite(fragment: BaseFragment) {
        if (!fragment.isDetached) {
            fragment.compositeDisposable.add(this)
        }
    }

}

